package peer.gui;

import java.util.LinkedList;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

public class NetworkConnectionModel implements TableModel
{
	public class PeerConnection
	{
		String address;
		int port;
		
		public PeerConnection(String address, int port)
		{
			this.address = address;
			this.port = port;
		}
	}

	LinkedList<PeerConnection> data = new LinkedList<PeerConnection>();
	String[] columnNames = {"IP Address", "Port"};
	Class[] columnClasses = {String.class, Integer.class};
	
	TableModelListener listener;

	public void addTableModelListener(TableModelListener listener)
	{
		this.listener = listener;
	}

	public Class<?> getColumnClass(int i)
	{
		return columnClasses[i];
	}

	public int getColumnCount()
	{
		return columnNames.length;
	}

	public String getColumnName(int i)
	{
		return columnNames[i];
	}

	public int getRowCount()
	{
		return data.size();
	}

	public Object getValueAt(int row, int column)
	{
		if(column == 0)
		{
			return data.get(row).address;
		}
		else if(column == 1)
		{
			return data.get(row).port;
		}
		return null;
	}

	public boolean isCellEditable(int row, int column)
	{
		return false;
	}

	public void removeTableModelListener(TableModelListener arg0)
	{
		// TODO Auto-generated method stub

	}

	public void setValueAt(Object arg0, int arg1, int arg2)
	{
		// TODO Auto-generated method stub

	}
	
	public void addConnection(String address, int port)
	{
		boolean exists = false;
		for (PeerConnection p : data)
		{
			if(p.address.equals(address) && p.port == port)
			{
				exists = true;
			}
		}
		if(!exists)
		{
			data.add(new PeerConnection(address, port));
			listener.tableChanged(new TableModelEvent(this, data.size(), data.size(), TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
		}
	}
	
	public boolean removeConnection(String address, int port)
	{
		//int index = data.indexOf(address);
		//String s = data.remove(index);
		int index = -1;
		for (int i = 0; i < data.size(); i++)
		{
			if(data.get(i).address.equals(address) && data.get(i).port == port)
			{
				index = i;
				data.remove(index);
			}
		}
		boolean r = false;
		if(index != -1)
		{
			listener.tableChanged(new TableModelEvent(this, index, index, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE));
			r = true;
		}
		return r;
	}

}
